<template>
  <div class="container">
    <el-dialog :title="dialog.dialogType === 'edit' ? '修改商超购货单' : '创建商超购货单'
      " :visible.sync="dialog.centerDialogVisible" width="1400px" center :lock-scroll="true" :before-close="hideDialog"
      @open="getData" @close="hideDialog">
      <el-form label-width="100px" label-position="left">
        <el-form-item label="供应商：">
          <el-select :disabled="dialog.dialogType === 'edit'" size="small" v-model="inside.value" :multiple="false"
            filterable remote center reserve-keyword placeholder="请选择供应商" :remote-method="insideRemoteMethod"
            :loading="inside.loading" @change="getOptionId(inside.value)">
            <el-option v-for="item in inside.options" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购员：">
          <el-select size="small" v-model="purchase.value" :disabled="purchase.type" :multiple="false" filterable remote
            center reserve-keyword placeholder="请选择采购员" :remote-method="insidePurchaseMethod" :loading="inside.loading"
            @change="getPurchase(purchase.value)">
            <el-option v-for="item in purchase.options" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配送中心：">
          <el-select size="small" :multiple="false" filterable remote center reserve-keyword v-model="selectList"
            placeholder="请搜索选择配送中心" @change="distribution(selectList)" :remote-method="selectListsRemoteMethod"
            :loading="selectLists.loading">
            <el-option v-for="item in selectLists.option" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品：">
          <el-select size="small" v-model="commodity.value" :multiple="false" filterable remote center reserve-keyword
            placeholder="请选择商品" :remote-method="insideCommodityMethod" :loading="inside.loading">
            <el-option v-for="item in commodity.options" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>

          <el-button size="mini" type="primary" class="handleSearch" icon="el-icon-zoom-in" @click="add()">添加</el-button>
          <el-button size="mini" type="primary" class="handleSearch" icon="el-icon-upload"
            @click="download()">模板下载</el-button>

          <el-upload class="upload-demo" style="display: inline; margin-left: 10px" action="#" :show-file-list="false"
            :http-request="handleAvatarSuccess">
            <el-button size="mini" type="primary" class="handleSearch" icon="el-icon-circle-plus">导入商品</el-button>
          </el-upload>
        </el-form-item>
        <el-table :data="tableData" border style="width: 100%" row-key="id" show-summary :summary-method="getSummaries"
          empty-text="暂无数据">
          <el-table-column prop="Name" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="BarCode" label="条形码" width="150px" align="center"></el-table-column>
          <el-table-column prop="Unit" width="100px" label="单位" align="center"></el-table-column>
          <el-table-column prop="reference_price" width="100px" label="入库参考价" align="center"></el-table-column>
          <el-table-column label="价格" align="center" width="150px">
            <template slot-scope="scope">
              <el-input-number size="small" :controls="false" v-model="scope.row.price"
                :max="scope.row.reference_price > 0 ? scope.row.reference_price : Infinity"
                @change="modificationPrice(scope)"></el-input-number>
            </template>
          </el-table-column>

          <el-table-column label="数量" align="center" width="150px">
            <template slot-scope="scope">
              <el-input-number size="small" @change="modificationNum(scope)" :controls="false"
                v-model="scope.row.num"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="SonCounts" label="入库规格" width="130px" align="center">
            <template slot-scope="scope">
              <div v-if="dialog.dialogType === 'edit'">
                {{ scope.row.rk_spec }}
              </div>
              <el-select v-else v-model="scope.row.rk_spec" @change="sonCount(scope)" placeholder="请选择">
                <el-option v-for="item in scope.row.SonCountsList" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
              <p v-if="scope.row.rk_spec != scope.row.rk_specs && dialog.dialogType != 'edit'" style="color: red">
                系统箱规为：{{ scope.row.rk_specs }}
              </p>
            </template>
          </el-table-column>

          <el-table-column prop="qty" width="100px" label="件数" align="center"></el-table-column>
          <el-table-column prop="total" width="100px" label="总金额" align="center"></el-table-column>
          <el-table-column label="生产日期" align="center" width="250px">
            <template slot-scope="scope">
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" @change="timeCenter(scope)"
                v-model="scope.row.produce_date" type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="保质期（天）" align="center" width="150px">
            <template slot-scope="scope">
              <el-input-number size="small" @change="timeCenter(scope)" :controls="false"
                v-model="scope.row.shelf_life"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="到期日" align="center" width="250px">
            <template slot-scope="scope">
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" @change="timeCenter(scope)"
                v-model="scope.row.due_date" type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" width="250px">
            <template slot-scope="scope">
              <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="scope.row.notes">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" align="center">
            <template slot-scope="scope">
              <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope)">删除</el-button>
              <el-button v-if="dialog.dialogType != 'edit'" size="mini" type="primary" class="handleSearch"
                icon="el-icon-circle-plus" @click="addSpec(scope)">添加规格</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-dialog width="400px" title="添加规格" center :visible.sync="spaceDialog" append-to-body @close="cancelSpec">
        <el-form label-width="100px" label-position="center">
          <el-form-item label="规格：">
            <el-input-number size="small" :controls="false" v-model="spec"></el-input-number>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelSpec">取 消</el-button>
          <el-button type="primary" @click="specNum()">确 定</el-button>
        </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { Loading } from "element-ui";
import { selectSupplierData } from "@/api/supplier/supplierList"; //供应商
// import { supplierList } from "@/api/supplier/supplierList";
import {
  // selectBuyerList,
  selectErpGoodsList,
  addBuyOrder,
  getBuyOrderGoods,
  // selectSupplierList,
  editBuyOrder,
  findAdminInfoUncheck,
  importBuyOrderGoods,
} from "@/api/putStorage/superPurchaseList";
import { getList } from "@/api/putStorage/putStotageList"; //采购员
// import { getSupplierBindGoods } from "@/api/commodity/commodityList"; //商品
import { selectErpGoodsDataNew } from "@/api/commodity/commodityList"; //商品
import { selectRdcData } from "@/api/select/select";
export default {
  props: {
    dialog: Object,
    dialogData: Object,
  },
  data() {
    return {
      formData: {
        supplier_id: "",
        supplier_code: "",
        supplier_name: "",
        goods: "",
        buyer_id: "",
        buyer_code: "",
        buyer_name: "",
      },
      inside: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      },
      selectLists: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      selectList: "",
      purchase: {
        innerVisible: false,
        options: [],
        value: "",
        type: false,
        list: [],
        loading: false,
      },
      commodity: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      },
      tableData: [],
      commodityList: [],
      spaceDialog: false,
      spec: "0",
      specId: "",
      search: {
        selectnamecode: "",
      },
      distributionData: {
        name: "",
        code: "",
        area_code: ''
      },
    };
  },
  methods: {
    //获取修改数据
    getData() {
      let data = {
        page: 1,
        limit: 100,
      };
      //是不是采购员
      findAdminInfoUncheck().then((res) => {
        if (res.data.admin_info.acc_type == 3) {
          this.purchase.value = res.data.admin_info.buyer;
          this.purchase.type = true;
        } else {
          this.purchase.type = false;
        }
      });
      //获取供应商列表
      selectSupplierData(data).then((res) => {
        this.inside.options = res.data.paginate.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.supplier_name}`,
            code: `${item.supplier_code}`,
          };
        });
      });
      //获取商超采购员列表
      getList(data).then((res) => {
        this.purchase.options = res.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.name}(${item.code})`,
            code: `${item.code}`,
          };
        });
      });

      //获取商品
      if (this.dialog.dialogType == "edit") {
        this.inside.value = this.dialogData.supplier_name;
        this.formData.supplier_id = this.dialogData.supplier_id;
        this.formData.supplier_code = this.dialogData.supplier_code;
        this.purchase.value =
          this.dialogData.buyer_name + "(" + this.dialogData.buyer_code + ")";
        this.formData.buyer_name =
          this.dialogData.buyer_name + "(" + this.dialogData.buyer_code + ")";
        this.formData.buyer_id = this.dialogData.buyer_id;
        this.formData.buyer_code = this.dialogData.buyer_code;
        this.selectList = this.dialogData.dcname;
        let datas = {
          id: this.dialog.id,
        };
        getBuyOrderGoods(datas).then((res) => {
          if (res.code == 0) {
            this.distributionData = {
              name: res.info.dcname,
              code: res.info.dccode,
              area_code: res.info.rdc_area_code,
            };
            res.data.forEach((item) => {
              this.tableData.push({
                price: parseFloat(item.price),
                num: item.count,
                qty: item.bos_qty,
                Name: item.name,
                Spec: item.spec,
                Code: item.goods_code,
                ProductId: item.goods_erp_id,
                Unit: item.unit,
                ClassCode: item.category_code,
                ClassName: item.category_name,
                BarCode: item.goods_bar_code,
                produce_date: item.produce_date,
                shelf_life: item.shelf_life,
                due_date: item.due_date,
                notes: item.notes,
                reference_price: parseFloat(item.reference_price),
                total:
                  item.price != 0 && parseFloat(item.count) != 0
                    ? (item.price * parseFloat(item.count)).toFixed(4)
                    : 0,
                rk_spec: item.rk_spec,
              });
            });
          }
        });
      }
      this.getselsetData();
    },
    getselsetData() {
      let data = {
        page: 1,
        limit: 500,
        code_or_name: this.search.selectnamecode,
      };
      //获取配送中心
      selectRdcData(data).then((res) => {
        if (res.data.paginate.data) {
          this.selectLists.option = res.data.paginate.data.map((item) => {
            return { value: `${item.d_code}`, label: `${item.d_name}`, area_code: `${item.area_code}` };
          });
        }
      });
    },
    // 嵌套搜索配送方式数据
    selectListsRemoteMethod(query) {
      if (query !== "") {
        this.houseList(query);
      } else {
        this.selectLists.option = [];
      }
    },
    //获取配送数据
    houseList(query) {
      this.search.selectnamecode = query;
      this.getselsetData();
    },
    getDatas() {
      let data = {
        goods_code: "",
        // supplier_code: this.formData.supplier_code,
        page: 1,
        limit: 100,
        is_can_use: 3
      };
      //获取商超商品列表
      selectErpGoodsDataNew(data).then((res) => {
        this.commodityList = res.data.paginate.data;
        this.commodity.options = res.data.paginate.data.map((item) => {
          return { value: `${item.Code}`, label: `${item.Name}` };
        });
      });
    },
    //时间计算
    timeCenter(scope, num) {
      if (scope.row.produce_date && scope.row.shelf_life) {
        var produce_date_stamp = new Date(scope.row.produce_date).getTime();
        var shelf_life_stamp = 86400000 * scope.row.shelf_life;
        var due_date_stamp = this.timestampToDatetime(produce_date_stamp + shelf_life_stamp)
        scope.row.due_date = due_date_stamp
      } else if (scope.row.produce_date && !scope.row.shelf_life && scope.row.due_date) {
        var produce_date_stamp = new Date(scope.row.produce_date).getTime();
        var due_date_stamp = new Date(scope.row.due_date).getTime();
        var shelf_life_stamp = Math.round((due_date_stamp - produce_date_stamp) / 86400000)
        scope.row.shelf_life = shelf_life_stamp
      } else if (!scope.row.produce_date && scope.row.shelf_life && scope.row.due_date) {
        var shelf_life_stamp = 86400000 * scope.row.shelf_life;
        var due_date_stamp = new Date(scope.row.due_date).getTime();
        var produce_date_stamp = this.timestampToDatetime(due_date_stamp - shelf_life_stamp)
        scope.row.produce_date = produce_date_stamp
      }

    },
    timestampToDatetime(timestamp) {
      let date = new Date(timestamp);
      let year = date.getFullYear();
      let month = ("0" + (date.getMonth() + 1)).slice(-2);
      let day = ("0" + date.getDate()).slice(-2);
      let hours = ("0" + date.getHours()).slice(-2);
      let minutes = ("0" + date.getMinutes()).slice(-2);
      let seconds = ("0" + date.getSeconds()).slice(-2);
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //获取供应商数据
    getSupplierList(query) {
      let data = {
        name: query,
        page: 1,
        limit: 100,
      };
      this.inside.loading = true;
      selectSupplierData(data).then((res) => {
        this.inside.list = res.data.paginate.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.supplier_name}`,
            code: `${item.supplier_code}`,
          };
        });
        this.inside.loading = false;
        this.inside.options = this.inside.list.filter((item) => {
          return (
            item.label.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
            item.code.toLowerCase().indexOf(query.toLowerCase()) > -1
          );
        });
      });
    },
    // 嵌套搜索供应商数据
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //选择供应商获取ID
    getOptionId(e) {
      let data = this.inside.options.filter((res) => {
        return res.value == this.inside.value;
      });
      this.formData.supplier_id = data[0].value;
      this.formData.supplier_code = data[0].code;
      this.formData.supplier_name = data[0].label;
    },
    // 嵌套搜索采购员数据
    insidePurchaseMethod(query) {
      if (query !== "") {
        this.getPurchaseList(query);
      } else {
        this.purchase.options = [];
      }
    },
    getPurchaseList(query) {
      let data = {
        key: query,
        page: 1,
        limit: 100,
      };
      this.purchase.loading = true;
      getList(data).then((res) => {
        this.purchase.list = res.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.name}(${item.code})`,
            code: `${item.code}`,
          };
        });
        this.purchase.loading = false;
        this.purchase.options = this.purchase.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      });
    },
    getPurchase(e) {
      let data = this.purchase.options.filter((res) => {
        return res.value == e;
      });
      this.formData.buyer_id = data[0].value;
      this.formData.buyer_code = data[0].code;
      this.formData.buyer_name = data[0].label;
    },
    // 嵌套搜索商品数据
    insideCommodityMethod(query) {
      if (query !== "") {
        if (this.distributionData.code) {
          this.commodity.value = '';
          this.getCommodityList(query, this.distributionData.code);
        } else {
          this.$message({
            type: "info",
            message: "请选择配送中心",
          });
        }

      } else {
        this.commodity.options = [];
      }
    },
    getCommodityList(query, code) {
      let data = {
        goods_code: query,
        page: 1,
        limit: 100,
        rdc_code: code,
        is_can_use: 3
      };
      this.purchase.loading = true;
      selectErpGoodsDataNew(data).then((res) => {
        this.commodityList = res.data.paginate.data;
        this.commodity.options = res.data.paginate.data.map((item) => {
          return { value: `${item.Code}`, label: `${item.Name}` };
        });
        console.log(this.commodity.options, 9999)
        this.commodity.loading = false;
      });
    },
    hideDialog() {
      this.dialog.centerDialogVisible = false;
      this.formData = {
        supplier_id: "",
        supplier_code: "",
        goods: "",
        buyer_id: "",
      };

      this.inside = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      };
      this.purchase = {
        innerVisible: false,
        options: [],
        value: "",
        type: false,
        list: [],
        loading: false,
      };
      this.commodity = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      };
      (this.selectLists = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      }),
        (this.selectList = "");
      this.tableData = [];
      this.commodityList = [];
      this.distributionData = {
        name: "",
        code: "",
        area_code: ''
      };
    },
    //添加规格
    addSpec(scope) {
      this.specId = scope.row.BarCode;
      this.spaceDialog = true;
    },
    cancelSpec() {
      this.spaceDialog = false;
      this.spec = 0;
      this.specId = "";
    },
    //规格确定
    specNum() {
      this.tableData.forEach((res, index) => {
        if (res.BarCode == this.specId) {
          res.SonCountsList.push({
            value: this.spec,
            label: this.spec,
          });
          this.$set(this.tableData, index, res);
          this.cancelSpec();
        }
      });
    },
    //商品添加
    add() {
      if (this.commodityList.length == 0) {
        this.$message({
          type: "info",
          message: "请选择商品",
        });
      } else {
        let data = this.commodityList.filter((res) => {
          return res.Code == this.commodity.value;
        });
        let bool = this.tableData.filter((res) => {
          return res.Code == data[0].Code;
        });
        if (bool.length > 0) {
          this.$message({
            type: "info",
            message: "该商品已添加",
          });
          return;
        } else {
          let sonArr = data[0].SonCounts.split(",");
          let sonObj = [];
          sonArr.forEach((res) => {
            if (res == 0) {
              if (data[0].rk_spec) {
                sonObj.push({
                  value: data[0].rk_spec,
                  label: data[0].rk_spec,
                });
              } else {
                sonObj.push({
                  value: 1,
                  label: 1,
                });
              }
            } else {
              if (data[0].rk_spec) {
                sonObj.push({
                  value: data[0].rk_spec,
                  label: data[0].rk_spec,
                });
              } else {
                sonObj.push({
                  value: res,
                  label: res,
                });
              }
            }
          });
          console.log(data, 787878)
          let price = 0;
          let reference_price = data[0].reference_price;

          if (reference_price && Object.keys(reference_price).length > 0 && reference_price[1] && reference_price[1][this.distributionData.area_code]) {
            console.log(8888)
            price = reference_price[1][this.distributionData.area_code].reference_price
          }
          this.tableData.push({
            // price: data[0].SalePrice,
            price: price,
            num: 0,
            qty: 0,
            total: 0,
            shelf_life: 0,
            rk_spec: data[0].rk_spec,
            rk_specs: data[0].rk_spec,
            SonCountsList: sonObj,
            BarCode: data[0].BarCode,
            Name: data[0].Name,
            Spec: data[0].Spec,
            Code: data[0].Code,
            ProductId: data[0].ProductId,
            Unit: data[0].Unit,
            ClassCode: data[0].ClassCode,
            ClassName: data[0].ClassName,
            produce_date: data[0].produce_date,
            reference_price: price,
            due_date: '',
            notes: ''
          });
        }
      }
    },

    // 商品删除
    handleDelete(scope) {
      this.tableData.forEach((res, index) => {
        if (res.Code == scope.row.Code) {
          this.tableData.splice(index, 1);
        }
      });
    },

    //修改数量
    modificationNum(scope) {
      if (scope.row.num) {
        scope.row.total = (scope.row.price * scope.row.num).toFixed(4);
        if (scope.row.rk_spec == 0) {
          scope.row.qty = scope.row.num;
        } else {
          scope.row.qty = (
            scope.row.num / parseFloat(scope.row.rk_spec)
          ).toFixed(4);
        }

        this.$set(this.tableData, scope.$index, scope.row);
      } else {
        scope.row.total = 0;
        scope.row.qty = 0;
        this.$set(this.tableData, scope.$index, scope.row);
      }
    },
    //修改价格
    modificationPrice(scope) {
      if (scope.row.price) {
        scope.row.total = (scope.row.price * scope.row.num).toFixed(4);
      } else {
        scope.row.total = 0;
        this.$set(this.tableData, scope.$index, scope.row);
      }
    },
    //导入商品
    handleAvatarSuccess(param) {
      if (this.formData.supplier_code) {
        let loading = Loading.service({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.1)",
        });
        let data = new window.FormData();
        data.append("goods_file", param.file);
        data.append("supplier_code", this.formData.supplier_code);
        data.append("rdc_code", this.distributionData.code);
        this.$axios
          .post("/smkapi/Buyorder/importBuyOrderGoods", data)
          .then((res) => {
            loading.close();
            if (res.data.code == 0) {
              this.$message({
                message: res.data.message || res.data.msg,
                type: "success",
              });
              if (res.data.data.length > 0) {
                this.tableData = [];
                res.data.data.forEach((result) => {
                  let sonArr = result.SonCounts.split(",");
                  let sonObj = [];
                  sonArr.forEach((res) => {
                    if (res == 0) {
                      sonObj.push({
                        value: 1,
                        label: 1,
                      });
                    } else {
                      sonObj.push({
                        value: res,
                        label: res,
                      });
                    }
                  });
                  result.price = result.zc_price || 0;
                  // result.numPrice = result.SalePrice || 0;
                  result.num = result.num || 0;
                  result.qty = result.bos_qty || 0;
                  result.total =
                    result.price != 0 && result.num != 0
                      ? (result.price * result.num).toFixed(4)
                      : 0;
                  result.rk_specs = result.rk_spec;
                  result.rk_spec = result.selectSonCounts;
                  // result.is_avg = true
                  result.SonCountsList = sonObj;
                  result.produce_date = result.produce_date;
                  result.due_date =  result.due_date;
                  result.notes = ''
                  result.reference_price = parseFloat(result.reference_price);
                  this.tableData.push(result);
                });
              }
            } else {
              this.$message({
                type: "info",
                message: res.data.msg,
              });
            }
          });
      } else {
        this.$message({
          type: "info",
          message: "请选择供应商",
        });
      }
    },
    sonCount(scope) {
      if (scope.row.num) {
        scope.row.total = (scope.row.price * scope.row.num).toFixed(4);
        if (scope.row.rk_spec == 0) {
          scope.row.qty = scope.row.num;
        } else {
          scope.row.qty = (
            scope.row.num / parseFloat(scope.row.rk_spec)
          ).toFixed(4);
        }

        this.$set(this.tableData, scope.$index, scope.row);
      } else {
        scope.row.total = 0;
        scope.row.qty = 0;
        this.$set(this.tableData, scope.$index, scope.row);
      }
    },
    download() {
      this.$confirm("是否下载模板?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/Buyorder/downLoadGoodsListTmp";
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    distribution(code) {
      let arr = this.selectLists.option.filter((item) => {
        return item.value == code;
      });
      this.distributionData = {
        name: arr[0].label,
        code: arr[0].value,
        area_code: arr[0].area_code
      };
    },
    indexNum(str) {
      let firstNum = str.indexOf("(");
      return str.slice(0, firstNum);
    },
    //合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (index != 6 && index != 7) {
            sums[index] = "";
          } else {
            sums[index] = sums[index].toFixed(4);
          }
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    //提交
    confirm() {
      if (this.formData.supplier_id == "") {
        this.$message({
          type: "info",
          message: "请选择供应商",
        });
      } else if (this.formData.buyer_id == "") {
        this.$message({
          type: "info",
          message: "请选择采购员",
        });
      } else if (this.distributionData.code == "") {
        this.$message({
          type: "info",
          message: "请选择配送中心",
        });
      } else if (this.tableData.length == 0) {
        this.$message({
          type: "info",
          message: "请选择商品",
        });
      } else {
        // return
        let table = [];
        this.tableData.forEach((res) => {
          table.push({
            goods_bar_code: res.BarCode,
            price: res.price,
            num: res.num,
            qty: res.qty,
            name: res.Name,
            spec: res.Spec,
            goods_code: res.Code,
            goods_erp_id: res.ProductId,
            unit: res.Unit,
            category_code: res.ClassCode,
            category_name: res.ClassName,
            rk_spec: res.rk_spec,
            produce_date: res.produce_date,
            shelf_life: res.shelf_life,
            due_date: res.due_date,
            notes: res.notes
          });
        });
        let data = {
          supplier_id: this.formData.supplier_id,
          supplier_code: this.formData.supplier_code,
          supplier_name: this.formData.supplier_name,
          buyer_code: this.formData.buyer_code,
          buyer_name: this.indexNum(this.formData.buyer_name),
          buyer_id: this.formData.buyer_id,
          dccode: this.distributionData.code,
          dcname: this.distributionData.name,
          goods: JSON.stringify(table),
        };
        // console.log(data);
        // return;
        if (this.dialog.dialogType == "edit") {
          data.id = this.dialog.id;
          editBuyOrder(data).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.msg || res.message,
              });
              this.$emit("upData");
              this.hideDialog();
            }
          });
        } else {
          addBuyOrder(data).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.msg || res.message,
              });
              this.$emit("upData");
              this.hideDialog();
            }
          });
        }
      }
    },
    //取消
    cancel() {
      this.hideDialog();
    },
  },
};
</script>
<style scoped>
.tab {
  display: flex;
}

.tab .el-form-item {
  flex: 1;
}
</style>
